/**
 * @description: 批量输入弹窗
 */

import { useEffect, useState } from "react";
import { Form, Input, message } from "antd";
import { CommonModal } from "@/views/components/CommonModal";
import { union } from "lodash";
import Style from "./index.module.less";

const { TextArea } = Input;

const BatchInputModal2 = ({ title = "批量输入", maxCount=500, label = "", handleCancel, handleOk }) => {
	const [form] = Form.useForm();
	//确定弹框关闭的类型
	const [isOk, setIsOk] = useState(false);

	const [open, setOpen] = useState(false);

	useEffect(() => {
		setOpen(true);
	}, [])

	const onOk = () => {
		form.validateFields().then(val => {
			const { areaValue } = val;
			if(!areaValue) {
				message.warning("输入框不能为空");
				return;
			}
			//通过换行或者逗号分隔并过滤掉空的
			const arr = areaValue.split(/\n|,|，/gi).filter(item => item.replace(/ /g, ""));
			if (arr.length == 0) {
				message.warning("输入框不能为空");
				return;
			}
			setIsOk(true);
			setOpen(false);
		});
	};

	const onCancel = () => {
		setOpen(false);
	}

	const afterClose = () => {
		if(isOk) {
            const val = form.getFieldsValue();
			const { areaValue } = val;
			//通过换行或者逗号分隔并过滤掉空的
			const arr = areaValue.split(/\n|,|，/gi).filter(item => item.replace(/ /g, ""));
			const item = union(arr.slice(0, maxCount)).join(",");
			handleOk(item);
		} else {
			handleCancel();
		}
	}

	return (
		<CommonModal title={{ title: title }} width={450} open={open} onOk={onOk} afterClose={afterClose} onCancel={onCancel}>
			<Form form={form}>
				<div className={Style.common_modal_content}>
					<Form.Item name="areaValue">
						<TextArea maxLength={1000} placeholder={`${label}，换行输入，最多支持${maxCount}条`} autoSize={{ minRows: 5, maxRows: 10 }} />
					</Form.Item>
				</div>
			</Form>
		</CommonModal>
	);
};

export default BatchInputModal2;
